(function (G) {
    const javaUrl = G.Storage.get('JAVAURL')
    G.vue({
        data: {
            type: 1, // 考核类型编号1：日常检查考核；2：月度集中考核；3：公众监督考核；4： 重大事项考核
            picList: [],
            deductionList: [],
            gradeTotal: 0,
            address: '',
            APIURL: G.Storage.get('APIURL'),
            deductionIdList: [],
            description: '',
            roadId: 0,
            units: [],
            unitIndex: 0,
            latitude: '',
            longitude: '',
            unitId: '',
            unitName: '',
            tabIndex:0,
            tabs:[],
            timer:0,
            unNow:false,
            time:''
        },
        methods: {
            changeTab(event){
                let index = event.currentTarget ? event.currentTarget.dataset.index : event
                this.setData({
                    tabIndex:index
                })
                this.getGrid()
            },
            bindinput(e) {
                console.log(e, 'eee')
                this.setData({
                    description: e.detail.value
                })
            },
            bindPickerunitChange(e) {
                console.log(e)
                const value = e.detail.value
                this.setData({
                    unitIndex:e.detail.value
                })
            },
            selectGrid(){
                let tab = this.data.tabs[this.data.tabIndex]
                if(this.data.timer){
                    clearInterval(this.data.timer)
                    this.data.timer = 0
                }
                this.selectComponent('#gridSelect').open({
                    latitude:this.data.latitude,
                    longitude:this.data.longitude,
                    address:this.data.address,
                    selectId:this.data.units[this.data.unitIndex][tab.value == 'grid' ? 'id' : 'inventoryId'],
                    tab
                })
            },
            changeGrid(event){
                if(!event.detail.units){//关闭按钮
                    this.data.timer = setInterval(()=>{
                        this.getLocation()
                    },1000 * 60 * 1)
                    return
                }
                this.setData({
                    units: event.detail.units,
                    unitIndex: event.detail.unitIndex,
                    dispatchUser:event.detail.userId
                })
                if(this.data.timer && event.detail.event != 1) {
                    clearInterval(this.data.timer)
                    this.data.timer = setInterval(()=>{
                        this.getLocation()
                    },1000 * 60 * 1)
                }
            },
            toSelectDeduction() {
                let that = this
                wx.navigateTo({
                    url: `/pages/check/deductionSelect/index?resourceTypeId=${this.data.tabs[this.data.tabIndex].ids}&type=${this.data.type}`,
                    events: {
                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                        acceptDataFromOpenedPage: function ({
                            list,
                            type,
                            resourceTypeId
                        }) {
                            console.log(list, type, '拿到数据')

                            let total = 0
                            let deductionIdList = []
                            let description = []
                            list.forEach(item => {
                                total += Number(item.grade)
                                deductionIdList.push(item.id)
                                description.push(item.name)
                            })
                            let tabIndex = 0
                            that.data.tabs.forEach((item,i) => {
                                if(item.ids.indexOf(resourceTypeId) >= 0){
                                    tabIndex = i
                                }
                            })
                            that.setData({
                                deductionList: list,
                                type: type,
                                gradeTotal: total.toFixed(2),
                                //description:description.join(';'),
                                deductionIdList
                            })
                            if(resourceTypeId && tabIndex != that.data.tabIndex) that.changeTab(tabIndex)
                        },

                    }
                })
            },
            // selectLocation() {
            //     let that = this
            //     wx.navigateTo({
            //         url: '/pages/check/selectRoadScope/index',
            //         events: {
            //             // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
            //             acceptDataAddress: function ({
            //                 item
            //             }) {
            //                 clearInterval(that.data.timer)
            //                 that.setData({
            //                     address: item.name,
            //                     roadId: item.id
            //                 })
            //             },

            //         }
            //     })
            // },
            // 删除图片
            delPic(e) {
                const {
                    index
                } = e.currentTarget.dataset

                let uploadList = [...this.data.picList]
                uploadList.splice(index, 1)

                this.setData({
                    picList: uploadList
                })

            },
            upload(e) {
                const {
                    type
                } = e.currentTarget.dataset
                let _self = this;

                if (this.data.picList.length >= 5) return wx.showToast({
                    title: '最多上传5张',
                    icon: 'none'
                })
                wx.chooseMedia({
                    count: 5,
                    mediaType: ['image'],
                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album','camera'], //从相册选择
                    success(res) {
                        console.log(res, '选择图片')
                        const tempFilePaths = res.tempFiles;
                        for (var k in tempFilePaths) {
                            _self.uploadRequest(tempFilePaths[k].tempFilePath)
                        }
                    },
                    error: function (e) {
                        console.log(e);
                    }
                });

            },
            uploadRequest(img) {
                let _self = this;

                if (this.data.picList.length >= 5) return wx.showToast({
                    title: '最多上传5张',
                    icon: 'none'
                })
                wx.showLoading({
                    title: '上传中...',
                })

                const uploadTask = wx.uploadFile({
                    url: G.Storage.get('APIURL') + '/upload',
                    filePath: img,
                    name: 'file',
                    header: {
                        'token': G.Storage.get('userInfo').token
                    },
                    success(rej) {

                        try {
                            let showUrl = JSON.parse(rej.data).id
                            let url = G.Storage.get('APIURL') + '/file/' + showUrl
                            console.log(url, 'url')
                            let uploadList = [..._self.data.picList, {
                                url,
                                showUrl
                            }]
                            console.log(uploadList, 'uploadList')

                            _self.setData({
                                picList: uploadList
                            })
                            wx.hideLoading()
                        } catch (e) {
                            //TODO handle the exception
                        }
                    },
                    fail(err) {
                        console.log(err)
                    }
                });


            },
            submit() {
                let {
                    type,
                    deductionIdList,
                    description,
                    picList,
                    gradeTotal,
                    latitude,
                    longitude,
                    unitIndex,
                    address
                } = this.data
                if (deductionIdList.length == 0) {
                    wx.showToast({
                        title: '请选择扣分项',
                        icon: 'none'
                    })
                    return
                } else if (picList.length == 0) {
                    wx.showToast({
                        title: '请上传图片',
                        icon: 'none'
                    })
                    return
                } else {
                    if(!description) {
                        description = this.data.deductionList[0].name
                        if(this.data.deductionList[1]) description += ';' + this.data.deductionList[1].name
                        if(this.data.deductionList[2]) description += ';' + this.data.deductionList[2].name
                    }
                    if(this.data.tabIndex) description += '(' + this.data.units[this.data.unitIndex].name + '-' + this.data.units[unitIndex].typeName + ')'
                    let imgUrlList = picList.map(item => item.url)
                    const params = {
                        deductionIdList,
                        description,
                        imgUrlList,
                        "number": gradeTotal,
                        type,
                        latitude,
                        longitude,
                        gridId:this.data.units[unitIndex].id,
                        address,
                        "userId": G.Storage.get('userInfo').userId
                    }
                    if(this.data.time) params.assessTime = G.date(this.data.time).Format('yyyy-MM-dd hh:mm:ss')
                    //上报权重
                    // if(this.data.units[unitIndex].inventoryId){
                    //     G.get(G.Storage.get('JAVAURL') + '/sample/addWeight', {
                    //         id: this.data.units[unitIndex].inventoryId,
                    //         weight: 2
                    //     }).then(res => {
                    //         console.log('--res', res);
                    //     })
                    // }
                    //上报位置
                    G.addClock(params)
                    G.post(javaUrl + '/assess/save', params).then(rej => {
                        if (rej.status == 200) {
                            wx.showToast({
                                title: '操作成功',
                            })
                            const eventChannel = this.getOpenerEventChannel()
                            eventChannel.emit("addRecord", {
                                id: rej.data
                            })
                            setTimeout(() => {
                                wx.navigateBack()
                            }, 2000)
                            let newUnClickedList = G.Storage.get('newUnClickedList')
                            if(newUnClickedList) {
                                if(newUnClickedList.length){
                                    wx.setStorage({
                                        key: 'imgList',
                                        data: newUnClickedList
                                      })
                                }else{
                                    wx.removeStorageSync('imgList')
                                }
                                G.Storage.remove('newUnClickedList')
                            }

                        } else {
                            wx.showToast({
                                title: rej.message,
                                icon: 'none'
                            })
                        }
                    })
                }
            },
            getDistance(lat1, lng1, lat2, lng2) {
                lat1 = lat1 || 0;
                lng1 = lng1 || 0;
                lat2 = lat2 || 0;
                lng2 = lng2 || 0;
                var rad1 = lat1 * Math.PI / 180.0;
                var rad2 = lat2 * Math.PI / 180.0;
                var a = rad1 - rad2;
                var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
                var r = 6378137;
                var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
                return distance;
            },
            getGrid(longitude,latitude,address){
                if(longitude){
                    this.setData({
                        latitude,
                        longitude,
                        address: address || this.data.address
                    })
                }else{
                    latitude = this.data.latitude
                    longitude = this.data.longitude
                    address = this.data.address
                }
                this.selectComponent('#gridSelect').getDefault({
                    latitude,
                    longitude,
                    address,
                    pageSize:1,
                    tab:this.data.tabs[this.data.tabIndex]
                })
            },
            selectLocation() {
                wx.chooseLocation({
                    latitude:this.data.latitude,
                    longitude:this.data.longitude,
                    success:res=>{
                        this.getGrid(res.longitude,res.latitude,res.address)
                    }
                })
            },
            getLocation() { 
                if(!this.data.unNow){
                    wx.getLocation({
                        type: 'gcj02',
                        success:res=> {
                            G.get('/v1/map/geocodeRegeo',{
                                latitude:res.latitude,
                                longitude:res.longitude
                            }).then(location => {
                                let address = location.regeocode ? location.regeocode.formatted_address : ''
                                this.getGrid(res.longitude,res.latitude,address)
                            })
                            if(!this.data.timer){
                                this.data.timer = setInterval(()=>{
                                    this.getLocation()
                                },1000 * 30)
                            }
                        }
                    })
                }else{
                    this.getGrid(this.data.longitude,this.data.latitude)
                }
            },
            onUnload(){
                if(this.data.timer) {
                    clearInterval(this.data.timer)
                    this.data.timer = 0
                }
            }
        },
        mounted(opt) {
            let data = { type:opt.type }
            let newClickedList = G.Storage.get('newClickedList')
            if(newClickedList && newClickedList.length){
                data.picList = newClickedList && newClickedList.length ? newClickedList : []
                data.latitude = newClickedList[0].latitude
                data.longitude = newClickedList[0].longitude
                data.address = newClickedList[0].address
                data.time = newClickedList.time
                data.unNow = true
                G.Storage.remove('newClickedList')
            }
            G.get('/model/grid',{},null,{storageName:'modelgrid'}).then(res => {
                data.tabs = res.resType.attr.actions
                this.setData(data)
                this.getLocation()
                this.loaded = true
            })
            
        }
    })
})(wx.$)